<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of MobileAction
 *
 * @author Administrator
 */
import('@.Service.AppService');
import('@.Service.MobileService');
import('@.Util.ConstantUtil');
import('@.Filter.BaseAction');
import('@.Service.SessionService');
import('@.Service.SubjectService');
import('@.Service.SubjectContentService');
import('@.Service.UserService');
import('@.Service.CommentService');
import('@.Service.AppTopService');
import('@.Service.NewsService');

class MobileAction extends BaseAction {

    function listApp() {
        $type = empty($_REQUEST['type']) ? 'game' : urldecode($_REQUEST['type']);

//        $type = '动作游戏';
        $offset = empty($_REQUEST['offset']) ? 0 : $_REQUEST['offset'];
        $limit = empty($_REQUEST['limit']) ? 10 : $_REQUEST['limit'];


        //排行榜数据
        if ('排行榜' == $type) {
            $appTopService = new AppTopService();

            $list = $appTopService->listAppTop($offset, $limit);

            $result = array('count' => 200, 'type' => $type, 'offset' => $offset, 'limit' => $limit, 'data' => $list);

            $this->ajaxReturn($result, ConstantUtil::$MOBILE_SUCCESS_TEXT, 1);
            return;
        }

        $appService = new AppService();
        $typeName = $appService->getAppTypeName($type);

        $count = 0;
        if ('游戏' != $typeName && '应用' != $typeName) {
            $count = $appService->countAppBySmallTypeName($type, $appName);
        } else {
            $count = $appService->countAppByTypeName($typeName, null);
        }
        $field = "app.id, app.name, app.app_icon, app.tag, app.version, app.price, app.see_num, app.size, app.datetime, app.download_url, app.content, concat(concat('http://www.baipaopao.com/index.php/Index/appInfo/id/', app.id), '.shtml') web_url";

        $list = null;
        if ('游戏' != $typeName && '应用' != $typeName) {
            $list = $appService->listAppBySmallTypeName($type, $appName, $offset, $limit, 'datetime desc', 1, $field);

            $list = $this->listConvertChinese($list);
        } else {
            $list = $appService->listAppByTypeName($typeName, $appName, $offset, $limit, 'datetime desc', 1, $field);

            $list = $this->listConvertChinese($list);
        }
        if (!empty($list)) {

            $result = array('count' => $count, 'type' => $type, 'offset' => $offset, 'limit' => $limit, 'data' => $list);

            $this->ajaxReturn($result, ConstantUtil::$MOBILE_SUCCESS_TEXT, 1);
        } else {
            $this->ajaxReturn(null, '数据读取失败', 0);
        }
    }

    /**
     * App 详细信息
     * @param type $id 
     */
    function findAppById() {
        $id = $_REQUEST['id'];
//        $offset = empty($_REQUEST['offset']) ? 0 : $_REQUEST['offset'];
//        $limit = empty($_REQUEST['limit']) ? 10 : $_REQUEST['limit'];

        $appService = new AppService();
        $fields = "id, app_icon, content_text, content_img, datetime, download_num, download_url, name, price, see_num, size, tag, version, flash, concat(concat('http://www.appbpp.com/index.php/Index/appInfo/id/', app.id), '.shtml') web_url";
        $app = $appService->findAppById($id, $fields);

        $app = $this->convertChinese($app);

        $commentService = new CommentService();
        //总评论数
        $commentCount = $commentService->countCommentByAId($id);
        $field = 'comment.comment, comment.dateTime, u.nick_name, u.avatar';
        $comments = $commentService->listCommentByAppId($id, '0,20', $field);

        $comms = array();
        foreach ($comments as $c) {
            $c['avatar'] = str_replace('..', '/App/Tpl/default', $c['avatar']);

            array_push($comms, $c);
        }
        $comments = $comms;
        if (!empty($app)) {
            $this->ajaxReturn(array('app' => $app, 'comment' => array('count' => $commentCount, 'comments' => $comments)), ConstantUtil::$MOBILE_SUCCESS_TEXT, 1);
        } else {
            $this->ajaxReturn(null, '该条数据不存在', 0);
        }
    }

    /**
     * 返回所有小分类每个分类当前的app数目和免费app的数目
     */
    function countAppType() {
        $mobileService = new MobileService();

        $field = 'app.app_icon';
        $result = $mobileService->listType($field);
        $this->ajaxReturn($result, ConstantUtil::$MOBILE_SUCCESS_TEXT, 1);
    }

    function search() {
        $name = trim(urldecode($_REQUEST['name']));
        $offset = empty($_REQUEST['offset']) ? 0 : $_REQUEST['offset'];
        $limit = empty($_REQUEST['limit']) ? 10 : $_REQUEST['limit'];

        if (empty($name)) {
            $this->ajaxReturn($app, ConstantUtil::$MOBILE_PARAMS_NONE, 0);
            return;
        }
        $appService = new AppService();

        $count = $appService->countSearch($name);

        $field = 'app.id, app.name, app.app_icon, app.tag, app.version, app.price, app.see_num, app.size, app.datetime, app.download_url, app.content';
        $apps = $appService->search($name, $offset . ',' . $limit, $field);

        $this->ajaxReturn(array('count' => $count, 'offset' => $offset, 'limit' => $limit, 'data' => $apps), ConstantUtil::$MOBILE_SUCCESS_TEXT, 1);
    }

    /**
     * 评论
     */
    function comment() {
        $uId = $_REQUEST['uId'];
        $aId = $_REQUEST['aId'];
        $commentText = $_REQUEST['comment'];
        if (empty($uId) || empty($aId) || empty($commentText)) {
            $this->ajaxReturn(null, '缺少参数', 0);
            return;
        }
        $uService = new UserService();
        $user = $uService->findUserById($uId);
        if (empty($user)) {
            $this->ajaxReturn(null, '用户不存在', 0);
            return;
        }
        $aService = new AppService();
        $app = $aService->findAppById($aId);
        if (empty($app)) {
            $this->ajaxReturn(null, '评论的应用不存在', 0);
            return;
        }

        $cService = new CommentService();
        $comment = $cService->findCommentByUIdAId($uId, $aId);
        if (empty($comment)) {
            $comment['user_id'] = $uId;
            $comment['app_id'] = $aId;
            $comment['comment'] = $commentText;
            $comment['datetime'] = ConstantUtil::date();

            $lastId = $cService->insert($comment);
            if (0 < $lastId) {
                $this->ajaxReturn(null, '评论成功', 1);
                return;
            }
        } else {
            $comment['comment'] = $commentText;
            $comment['datetime'] = ConstantUtil::date();
            $lastId = $cService->update($comment);
            if (0 < $lastId) {
                $this->ajaxReturn(null, '评论成功', 1);
                return;
            }
        }

        $this->ajaxReturn(null, '评论失败', 0);
    }

    /**
     * 访问量
     */
    function visits() {
        $sessionService = new SessionService();
        $appService = new AppService();

        $visitsCount = $sessionService->count();
        $appCount = $appService->count();


        $this->ajaxReturn(array('visitsCount' => $visitsCount, 'appCount' => $appCount));
    }

    /**
     * 获取顶级类型
     */
    function listRootType() {
        $typeService = new TypeService();

        $this->ajaxReturn($typeService->listRootTypes(), ConstantUtil::$MOBILE_SUCCESS_TEXT, 1);
    }

    /**
     * 获取子类型
     * @param type $id 
     */
    function listChildTypeById() {
        $id = $_REQUEST['id'];
        $typeService = new TypeService();
        $types = $typeService->listChildTypesByRootTypeId($id);
        if (!empty($types)) {
            $this->ajaxReturn($types, ConstantUtil::$MOBILE_SUCCESS_TEXT, 1);
        } else {
            $this->ajaxReturn($types, '该条数据不存在', 0);
        }
    }

    function addToken() {
        $token = $_REQUEST['token'];
        if (empty($token)) {
            $this->ajaxReturn(null, 'token 不存在', 0);
            return;
        }
        $mobileService = new MobileService();

        $mobile = $mobileService->findMobileByToken($token);
        if (empty($mobile)) {
            $mobile = array('token' => $token, 'datetime' => date('Y-m-d H:m:s'));

            $mobileService->insert($mobile);
            $this->ajaxReturn(null);
        } else {
            $this->ajaxReturn(null, 'token 号已存在', 0);
        }
    }

    function clearToken() {
        $token = $_REQUEST['token'];
        if (empty($token)) {
            $this->ajaxReturn(null, 'token 不存在', 0);
            return;
        }
        $mobileService = new MobileService();

        $mobile = $mobileService->findMobileByToken($token);
        if (empty($mobile)) {
            $this->ajaxReturn(null, 'token 不存在', 0);
            return;
        }

        $mobile['badge'] = 0;
        $mobileService->update($mobile);
        $this->ajaxReturn(null);
    }

    //Mobile Login
    function login() {
        $email = $_REQUEST['email'];
        $password = $_REQUEST['password'];
        if (empty($email) || empty($password)) {
            $this->ajaxReturn(null, '用户名或密码为空', 0);
            return;
        }

        $uService = new UserService();
        $user['email'] = $email;
        $user['password'] = $password;
        $user['enabled'] = 1;

        $user = $uService->findUserByLogin($user);
        if (empty($user)) {
            $this->ajaxReturn(null, '用户名或密码不正确', 0);
            return;
        }

        $user['password'] = '';
        $this->ajaxReturn($user);
    }

    //Mobile register
    function register() {
        $email = $_REQUEST['email'];
        $nickname = $_REQUEST['nickname'];
        $password = $_REQUEST['password'];

        if (empty($email) || empty($password) || empty($nickname)) {
            $this->ajaxReturn(null, '用户名,昵称或密码为空', 0);
            return;
        }

        $uService = new UserService();
        $user = $uService->findUserByEmail($email);
        if (!empty($user)) {
            $this->ajaxReturn(null, '邮箱已存在', 0);
            return;
        }

        $user['email'] = $email;
        $user['nick_name'] = $nickname;
        $user['password'] = $password;

        $lastId = $uService->insert($user);
        if (0 < $lastId) {
            $user['password'] = '';
            $this->ajaxReturn($user);
        } else {
            $this->ajaxReturn(null, '未注册成功，稍后再试', 0);
        }
    }

    //专题
    function subject() {
        $offset = empty($_REQUEST['offset']) ? 0 : $_REQUEST['offset'];
        $limit = empty($_REQUEST['limit']) ? 10 : $_REQUEST['limit'];
        $sService = new SubjectService();
        $count = $sService->countSubject(-1);
        $list = $sService->listSubject(-1, $offset . ', ' . $limit, '*');

        $this->ajaxReturn(array('count' => $count, 'data' => $list));
    }

    //专题下集合
    function subjectList() {
        $id = $_REQUEST['id'];
        $offset = empty($_REQUEST['offset']) ? 0 : $_REQUEST['offset'];
        $limit = empty($_REQUEST['limit']) ? 10 : $_REQUEST['limit'];
        if (empty($id)) {
            $this->ajaxReturn(null, '主题Id不存在', 0);
            return;
        }
        $subjectService = new SubjectService();

        $scService = new SubjectContentService();
        $subject = $subjectService->findSubjectById($id);

        $count = $scService->countSubjectContentBySId($id);
        $field = 'app_icon, name, score, price, content, id';
        $list = $scService->listSubjectContentBySId($id, $offset . ', ' . $limit, $field);

        $this->ajaxReturn(array('count' => $count, 'data' => $list));
    }

    //专题内容
    function subjectContent() {
        $id = $_REQUEST['id'];
        if (empty($id)) {
            $this->ajaxReturn(null, '主题Id不存在', 0);
            return;
        }
        $scService = new SubjectContentService();
        $field = 'app_icon, content_img, content_text, download_url, id, install_num, name, price, score, score_num, size, subject_id, system, type, want_num';
        $sc = $scService->findSubjectById($id, $field);

        $this->ajaxReturn($sc);
    }

    function listNews() {
        $offset = empty($_REQUEST['offset']) ? 0 : $_REQUEST['offset'];
        $limit = empty($_REQUEST['limit']) ? 10 : $_REQUEST['limit'];
        $newsService = new NewsService();

        $count = $newsService->countMessages();
        $field = 'id, name, author, icon, content, datetime, module, read_num';
        $list = $newsService->listMessages($offset, $limit, 'datetime desc', $field);

        $listT = array();
        foreach ($list as $l) {
            if (!empty($l['content']) && 70 < mb_strlen($l['content'], 'UTF-8')) {
                $l['content'] = mb_substr($l['content'], 0, 70, 'UTF-8');

                array_push($listT, $l);
            }
        }

        $this->ajaxReturn(array('count' => $count, 'data' => $listT));
    }

    function news() {
        $id = $_REQUEST['id'];
        if (empty($id)) {
            $this->ajaxReturn(null, '参数不存在', 0);
            return;
        }

        $newsService = new NewsService();
        $news = $newsService->findMessageById($id);

        $this->ajaxReturn($news);
    }

    /**
     * 去除类型 大小 值前的中文
     * @param type $app 
     */
    private function convertChinese($app) {
        $size = $app['size'];
        $version = $app['version'];

        $size = str_replace('大小: ', '', $size);
        $version = str_replace('系统: ', '', $version);

        $a = $app;
        $a['size'] = $size;
        $a['version'] = $version;

        return $a;
    }

    /**
     * 批量 去除类型 大小 值前的中文
     * @param type $apps 
     */
    private function listConvertChinese($apps) {
        $a = array();
        foreach ($apps as $app) {
            array_push($a, $this->convertChinese($app));
        }

        return $a;
    }

}

?>
